package com.danskin.wechat.webapi;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.wxbase.wxtoken.JwTokenAPI;
import org.jeewx.api.wxuser.user.JwUserAPI;
import org.jeewx.api.wxuser.user.model.Wxuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.entity.WxFansCard;
import com.danskin.wechat.entity.WxFansInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.WxFansInfoService;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.EncryptUtil;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.StringUtil;

/**
 * 公众号对外开放接口
 * 
 * @author Allen Liu
 *
 */
@RestController
@RequestMapping("api/wechat/mp")
public class WechatMPController extends BaseApiController {

	@Autowired
	private TaskExecutor executor;

	@Autowired
	private WxFansInfoService wxFansInfoService;

	/**
	 * 获取公众号AccessToken
	 */
	@RequestMapping(value = "getAccessToken/{appId}", method = RequestMethod.GET)
	public AccessResponse<String> getAccessToken(@PathVariable("appId") String appId, HttpServletRequest request) {
		String accessToken = this.getMPAccessToken(appId);
		return new AccessResponse<String>("0", "ok", accessToken);
	}

	/**
	 * 获取公众号JsApi所需参数
	 * 
	 * @param openId
	 * @param empId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getJsApiTicket/{appId}", method = RequestMethod.GET)
	public AccessResponse<String> getJsApiTicket(@PathVariable("appId") String appId, HttpServletRequest request) {
		String ticket = getJsApiTicket(appId);
		return new AccessResponse<String>("0", "ok", ticket);
	}

	/**
	 * 获取公众号jsapi签名
	 * 
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getJsApiSignature/{appId}", method = RequestMethod.POST)
	public Object getJsApiSignature(@PathVariable("appId") String appId, @RequestBody Map<String, Object> map,
			HttpServletRequest request) {

		if (false == this.isValid("url", map)) {
			return this.getError("url不能为空");
		}
		// jssha('jsapi_ticket=' + data.data + '&noncestr=' + nonceStr +
		// '&timestamp=' + timestamp + '&url=' + url)
		String url = map.get("url").toString();
		String jsapi_ticket = getJsApiTicket(appId);

		String noncestr = StringUtil.getShortUUID();
		long timestamp = DateUtils.getMillis() / 1000;
		String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
				+ url;
		String signature = EncryptUtil.SHA1(str);

		JSONObject json = new JSONObject();
		json.put("jsapi_ticket", jsapi_ticket);
		json.put("noncestr", noncestr);
		json.put("timestamp", timestamp);
		json.put("signature", signature);
		json.put("url", url);
		LogUtil.info(json.toJSONString());
		return new AccessResponse<Object>("0", "ok", json);
	}

	/**
	 * 获取公众号CardJsApi所需参数
	 * 
	 * @param openId
	 * @param empId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getCardApiTicket/{appId}", method = RequestMethod.GET)
	public AccessResponse<String> getCardApiTicket(@PathVariable("appId") String appId, HttpServletRequest request) {
		String ticket = getCardApiTicket(appId);
		return new AccessResponse<String>("0", "ok", ticket);
	}

	/**
	 * 获取公众号CardJsApi所需参数
	 * 
	 * @param openId
	 * @param empId
	 * @param request
	 * @return
	 * @throws WexinReqException
	 */
	@RequestMapping(value = "getUserInfo/{appId}", method = RequestMethod.GET)
	public JSONObject getUserInfo(@PathVariable("appId") String appId, @RequestParam("code") String code,
			@RequestParam("scope") String scope, HttpServletRequest request) throws WexinReqException {

		String component_access_token = this.getComponentAccessToken();
		JSONObject json = WeiXinOpenApiClient.createInstance().getOAuth2AccessToken(component_access_token,
				COMPONENT_APPID, appId, code);

		if (scope.equals("snsapi_base")) {

			return json;
		}

		JSONObject user = WeiXinOpenApiClient.createInstance().getSnsUserInfo(json.getString("access_token"),
				json.getString("openid"));

		final JSONObject myUser = user;
		final String myAppId = appId;
		executor.execute(new Runnable() {

			@Override
			public void run() {
				if (myUser != null) {
					WxMediaPlatform mp = wechatOpService.queryMediaPlatformByAppId(myAppId);
					if (mp != null) {
						WxFansInfo fansInfo = wxFansInfoService.getWxFansInfoByOpenId(myUser.getString("openid"));
						wechatOpService.saveFansInfo(myUser, fansInfo, mp.getId(), null);
					}
				}
			}
		});

		return user;
	}

	// @RequestMapping(value = "activateMemberCard/{appId}", method =
	// RequestMethod.POST)
	// public JSONObject activateMemberCard(@PathVariable("appId") String appId,
	// @RequestParam("openId") String openId,
	// HttpServletRequest request) throws WexinReqException {
	//
	// WxFansCard card = wechatOpService.queryFansCard(openId, WX_CARD_ID, "");
	// if (card != null) {
	// String accessToken = super.getMPAccessToken(appId);
	// JSONObject json =
	// WeiXinOpenApiClient.createInstance().activateMemberCard(accessToken,
	// card.getWxCardId(), card.getUserCardCode(),"");
	//
	// return json;
	// }
	// return this.getError("该客户还有没会员卡");
	// }

	// @RequestMapping(value = "updateMemberCard/{appId}", method =
	// RequestMethod.POST)
	// public JSONObject updateMemberCard(@PathVariable("appId") String appId,
	// @RequestParam("openId") String openId,
	// HttpServletRequest request) throws WexinReqException {
	//
	// WxFansCard card = wechatOpService.queryFansCard(openId, WX_CARD_ID, "");
	// if (card != null) {
	// String accessToken = super.getMPAccessToken(appId);
	// JSONObject json =
	// WeiXinOpenApiClient.createInstance().activateMemberCard(accessToken,
	// card.getWxCardId(), card.getUserCardCode(),"");
	//
	// return json;
	// }
	// return this.getError("该客户还有没会员卡");
	// }
}
